<?php defined('SYSPATH') or die('No direct script access.');


/**
 * 公用类
 *
 * @author: xiadx
 * @date: 2013-04-01
 * @update:
 * @version:    $Id: Utility.php 1209 2015-12-17 02:52:40Z xiadx $
 */
class Utility
{
    /**
     *   生成JSON格式的正确消息
     *
     * @access  public
     * @param
     * @return  void
     */
    public static function jsonResult($content, $message = '', $append = array())
    {
        self::jsonResponse($content, 0, $message, $append);
    }

    /**
     * 创建一个JSON格式的错误信息
     *
     * @access  public
     * @param   string $msg
     * @return  void
     */
    public static function jsonError($msg)
    {
        self::jsonResponse('', 1, $msg);
    }

    /**
     * 创建一个JSON格式的数据
     *
     * @access  public
     * @param   string $content
     * @param   integer $error
     * @param   string $message
     * @param   array $append
     * @return  void
     */
    private static function jsonResponse($content = '', $error = "0", $message = '', $append = array())
    {

        $res = array('error' => $error, 'message' => $message, 'content' => $content);
        if (!empty($append)) {
            foreach ($append AS $key => $val) {
                $res[$key] = $val;
            }
        }
        $val = json_encode($res);
        exit($val);
    }

    /**
     *  API接口：生成JSON格式的正确消息
     * @param string $data 数据
     * @param string $msg 提示消息
     * @param array $append
     */
    public static function apiJsonResult($data, $msg = '', $compression_http_data = 'on', $append = array())
    {
        self::apiJsonResponse($data, '200', $msg, $append, $compression_http_data);
    }

    /**
     *  API接口：创建一个JSON格式的错误信息
     * @param string $error 错误代码
     * @param string $msg 提示消息
     */
    public static function apiJsonError($error, $msg)
    {
        self::apiJsonResponse('', $error, $msg);
    }

    /**
     * 创建一个JSON格式的数据
     *
     * @access  public
     * @param   string $data
     * @param   integer $error
     * @param   string $msg
     * @return  void
     */
    private static function apiJsonResponse($data = '', $error = '200', $msg = '', $append = array())
    {

        $res = array('error' => (string)$error, 'msg' => $msg, 'data' => $data);
        if (!empty($append)) {
            foreach ($append AS $key => $val) {
                $res[$key] = $val;
            }
        }
        $val = json_encode($res);
        /*add by xiadx 压缩数据*/
        $compression_http_data = isset($_REQUEST['compression_http_data']) ? $_REQUEST['compression_http_data'] : 'off';
        $ret_str = self::compress($val, $compression_http_data);
        exit($ret_str);
    }

    /**
     * 创建一个JSON格式的数据
     *
     * @access  public
     * @param   string $data
     * @param   integer $error
     * @param   string $msg
     * @return  void
     */
    public static function apiJsonResultExtends($data = [])
    {
        if (isset($data['error'])) {
            $data['error'] = (string)$data['error'];
        }
        $val = json_encode($data);
        /*add by xiadx 压缩数据*/
        if(!isset($_REQUEST['compression_http_data']))
        {
            $_REQUEST['compression_http_data'] = "off";
        }
        $compression_http_data = $_REQUEST['compression_http_data'] ? : 'off';
        $ret_str = self::compress($val, $compression_http_data);
        exit($ret_str);
    }

    /**
     *   生成JSONP格式的正确消息
     *
     * @access  public
     * @param
     * @return  void
     */
    public static function jsonpResult($jsonpcallback, $content, $message = '', $append = array())
    {
        self::jsonpResponse($jsonpcallback, $content, 0, $message, $append);
    }

    /**
     * 创建一个JSON格式的错误信息
     *
     * @access  public
     * @param   string $msg
     * @return  void
     */
    public static function jsonpError($jsonpcallback, $msg)
    {
        self::jsonpResponse($jsonpcallback, '', 1, $msg);
    }

    /**
     * 创建一个JSONP格式的数据
     *
     * @access  public
     * @param   string $content
     * @param   integer $error
     * @param   string $message
     * @param   array $append
     * @return  void
     */
    private static function jsonpResponse($jsonpcallback, $content = '', $error = "0", $message = '', $append = array())
    {

        $res = array('error' => $error, 'message' => $message, 'content' => $content);
        if (!empty($append)) {
            foreach ($append AS $key => $val) {
                $res[$key] = $val;
            }
        }
        $val = $jsonpcallback . '(' . json_encode($res) . ')';
        exit($val);
    }

    /**
     *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
     *
     * @access  public
     * @param   string $str 待转换字串
     *
     * @return  string       $str         处理后字串
     */
    public static function makeSemiangle($str)
    {
        $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
            '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
            'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
            'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
            'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
            'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
            'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
            'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
            'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
            'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
            'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
            'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
            'ｙ' => 'y', 'ｚ' => 'z',
            '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
            '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
            '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
            '》' => '>',
            '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
            '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
            '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
            '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
            '　' => ' ');

        return strtr($str, $arr);
    }


    /**
     * 判断IPv4
     * @param $ip
     * @return bool
     */
    public static function is_ipaddress($ip)
    {
        $reg = '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$';
        return preg_match('#' . $reg . '#isU', $ip, $matches);
    }

    /**
     * 判断utf8
     * @param $val
     * @return bool
     */
    public static function is_utf8($val)
    {
        // From http://w3.org/International/questions/qa-forms-utf-8.html
        return preg_match('%^(?:
[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $val);
    }

    /**
     * 36位UUID
     * @return string
     */
    public static function uuid()
    {
        // The field names refer to RFC 4122 section 4.1.2
        return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
            mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
            mt_rand(0, 65535), // 16 bits for "time_mid"
            mt_rand(0, 4095), // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
            bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
            // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
            // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
            // 8 bits for "clk_seq_low"
            mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
        );
    }

    /**
     * 32位UUID，无-横杠
     * @return string
     */
    public static function guid()
    {
        // The field names refer to RFC 4122 section 4.1.2
        return sprintf('%04x%04x%04x%03x4%04x%04x%04x%04x',
            mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
            mt_rand(0, 65535), // 16 bits for "time_mid"
            mt_rand(0, 4095), // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
            bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
            // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
            // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
            // 8 bits for "clk_seq_low"
            mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
        );
    }

    /**
     * 使用gzcompress对Json字符串进行解压缩
     * @param  $str_json
     * @param  $compression_http_data
     * @return $return_value
     */
    public static function uncompress($str_json,$compression_http_data)
    {
        if(empty($str_json))
        {
            return "";
        }

        $return_value = $str_json;
        if(!empty($compression_http_data) && $compression_http_data == "on")
        {
            // json字符串解析为数组
            $arr = json_decode($str_json);
            // 数组转化为字符串(经前台压缩过的)
            $str_compressed = self::getStringFromBytes($arr);
            // 压缩次数
            $count = 1;
            if(empty($count)||$count<1)
            {
                $count = 1;
            }
            // 得到解压缩的字符串
            for($i = 0; $i < $count; $i++)
            {
                $str_uncompressed = gzuncompress($str_compressed);
            }

            // 空数据
            if($str_uncompressed == "[]")
            {
                $return_value = "";
            }
            else
            {
                $return_value = $str_uncompressed;
            }
        }
        return $return_value;
    }

    // 使用gzcompress对字符串进行压缩
    /**
     * 使用gzcompress对字符串进行压缩
     * @param  $str
     * @param  $compression_http_data
     * @return $str
     */
    public static function compress($str,$compression_http_data)
    {


        // 是否开启移动护理数据传输压缩机制
        if(!empty($compression_http_data) && $compression_http_data == "on")
        {
            // 压缩级别,压缩次数
            $level = -1;
            $count = 1;
            if(empty($level)||$level<-1||$level>9)
            {
                $level = -1;
            }
            if(empty($count)||$count<1)
            {
                $count = 1;
            }
            for($i = 0; $i < $count; $i++)
            {
                $str = gzcompress($str,$level);
            }
        }
        return $str;
    }

    // 字节数组转化为字符串
    /**
     * 字节数组转化为字符串
     * @param  $bytes
     * @return $str
     */
    public static function getStringFromBytes($bytes)
    {
        $str = '';
        foreach($bytes as $ch)
        {
            $str .= chr($ch);
        }
        return $str;
    }

    /**
     * @desc:获取下载时间间隔查询条件（字符串）
     * @param:field 字段名称
     * @param:interval 时间间隔数组
     * @return:sql_where 返回查询条件
     */
    public static function getIntervalSqlString($field,$interval)
    {
        if(empty($interval["value"])||empty($interval["unit"]))
        {
            $interval["value"] = "24";
            $interval["unit"] = "hour";
        }

        $value = $interval["value"];
        $unit = $interval["unit"];
        $sql_where = "";

        if(strtolower($unit) == "hour")
        {
            // 最近x小时
            $sql_where = $field." >= DATE_SUB(now(), INTERVAL ".$value." HOUR)";
        }
        else if(strtolower($unit) == "day")
        {
            // 最近x天
            $sql_where = $field.$operator." >= DATE_SUB(CURDATE(), INTERVAL ".$value." DAY)";
        }else if(strtolower($unit) == "minute"){
            $sql_where = $field." >= DATE_SUB(now(), INTERVAL ".$value." MINUTE)";
        }
        else
        {
            // 默认最近24小时
            $sql_where = $field.$operator." >= DATE_SUB(now(), INTERVAL 24 HOUR)";
        }

        return $sql_where;
    }

    /**
     * @desc:获取下载时间间隔查询条件（字符串）
     * @param:field 字段名称
     * @param:interval 时间间隔数组
     * @return:sql_where 返回查询条件
     */
    public static function getIntervalSqlArray($field,$interval)
    {
        if(empty($interval["value"])||empty($interval["unit"]))
        {
            $interval["value"] = "24";
            $interval["unit"] = "hour";
        }

        $value = $interval["value"];
        $unit = $interval["unit"];
        $sql_where = '';

        if(strtolower($unit) == "hour")
        {
            // 最近x小时
            $sql_where = "DATE_SUB(now(), INTERVAL ".$value." HOUR)";
        }
        else if(strtolower($unit) == "day")
        {
            // 最近x天
            $sql_where = " DATE_SUB(CURDATE(), INTERVAL ".$value." DAY)";
        }else if(strtolower($unit) == "minute"){
            $sql_where = "DATE_SUB(now(), INTERVAL ".$value." MINUTE)";
        }
        else
        {
            // 默认最近24小时
            $sql_where = " DATE_SUB(now(), INTERVAL 24 HOUR)";
        }

        return $sql_where;
    }

    /**
     * Explode the "value" and "key" arguments passed to "pluck".
     *
     * @param  string|array $value
     * @param  string|array|null $key
     * @return array
     */
    public static function explodePluckParameters($value, $key)
    {
        $value = is_array($value) ? $value : explode('.', $value);

        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);

        return [$value, $key];
    }

    /**
     * Pluck an array of values from an array.
     *
     * @param  array $array
     * @param  string|array $value
     * @param  string|array|null $key
     * @return array
     */
    public static function array_pluck($array, $value, $key = null)
    {
        $results = [];

        list($value, $key) = self::explodePluckParameters($value, $key);

        foreach ($array as $item) {
            $itemValue = self::data_get($item, $value);

            // If the key is "null", we will just append the value to the array and keep
            // looping. Otherwise we will key the array using the value of the key we
            // received from the developer. Then we'll return the final array form.
            if (is_null($key)) {
                $results[] = $itemValue;
            } else {
                $itemKey = self::data_get($item, $key);

                $results[$itemKey] = $itemValue;
            }
        }

        return $results;
    }

    public static function data_get($target, $key, $default = null)
    {
        if (is_null($key)) {
            return $target;
        }

        $key = is_array($key) ? $key : explode('.', $key);

        foreach ($key as $segment) {
            if (is_array($target)) {
                if (!array_key_exists($segment, $target)) {
                    return value($default);
                }

                $target = $target[$segment];
            } elseif ($target instanceof ArrayAccess) {
                if (!isset($target[$segment])) {
                    return value($default);
                }

                $target = $target[$segment];
            } elseif (is_object($target)) {
                if (!isset($target->{$segment})) {
                    return value($default);
                }

                $target = $target->{$segment};
            } else {
                return value($default);
            }
        }

        return $target;
    }

    /**
     * [转换为终端本地的数据库执行sql字符串]
     * @param  array  $data      [需要转换的数据]
     * @param  [type] $table     [终端本地表的名称]
     * @param  [type] $key_name  [返回json的节点名称]
     * @param  array  $field_arr [表的字段数组]
     * @return [type]            [description]
     */
    public static function formatToSqlStr($data = array(), $table, $key_name, $field_arr = [])
    {
        $async_result = [];
        if (empty($data)) {
            return $async_result;
        }
        $field_str = implode(',', $field_arr);
        /*$select_field_str = '';
        $count = count($field_arr);
        for ($i=0; $i < $count; $i++) {
            $select_field_str .= "'%s',";
        }
        // 去除最后一个逗号
        $select_field_str = rtrim($select_field_str, ',');*/

        $replace = "REPLACE INTO $table ($field_str) SELECT ";
        $union_all = " union all SELECT ";
        // 一条SQL语句执行200条记录
        $tiaoshu = 200;
        $count = count($data);
        $number = ceil($count/$tiaoshu);

        for ($i=0; $i < $number; $i++) {
            $value = $i * $tiaoshu; //取到哪一条
            if ($number > 1 ) {
                //取出指定数目的数组
                $data_array_slice = array_slice($data,$value,$tiaoshu);
            } else
                $data_array_slice = $data;

            foreach($data_array_slice as $key=>$value){
                $val_str = '';
                foreach ($field_arr as $field) {
                    /*if (!get_magic_quotes_gpc())
                        $str = addslashes($value[$field]);
                    else*/
                    $str = (string)$value[$field];
                    $val_str .= "'$str',";
                }
                // 去除最后一个逗号
                $val_str = rtrim($val_str, ',');
                if($key == 0){
                    $async_result[$key_name][$i] = $replace . $val_str;
                }
                else{
                    $async_result[$key_name][$i] .= $union_all . $val_str;
                }
            }
        }
        return $async_result;
    }

    /**
     * [转换为终端本地的数据库执行sql字符串]
     * @param  array  $data      [需要转换的数据]
     * @param  [type] $table     [终端本地表的名称]
     * @param  [type] $key_name  [返回json的节点名称]
     * @param  array  $field_arr [表的字段数组]
     * @return [type]            [description]
     */
    public static function formatToSqlStrExtends($data = array(), $table, $key_name, $field_arr = [])
    {
        $async_result = [];
        if (empty($data)) {
            return $async_result;
        }
        $field_str = implode(',', $field_arr);

        $replace = "REPLACE INTO $table ($field_str) SELECT ";
        $union_all = " union all SELECT ";
        // 一条SQL语句执行200条记录
        $tiaoshu = 200;
        $count = count($data);
        $number = ceil($count/$tiaoshu);

        for ($i=0; $i < $number; $i++) {
            $value = $i * $tiaoshu; //取到哪一条
            if ($number > 1 ) {
                //取出指定数目的数组
                $data_array_slice = array_slice($data,$value,$tiaoshu);
            } else
                $data_array_slice = $data;

            foreach($data_array_slice as $key=>$value){
                $val_str = '';
                foreach ($field_arr as $field) {
                    /*if (!get_magic_quotes_gpc())
                        $str = addslashes($value[$field]);
                    else*/
                    $str = (string)$value[$field];
                    $val_str .= "'$str',";
                }
                // 去除最后一个逗号
                $val_str = rtrim($val_str, ',');
                if($key == 0){
                    $async_result[$i] = $replace . $val_str;
                }
                else{
                    $async_result[$i] .= $union_all . $val_str;
                }
            }
        }
        return $async_result;
    }

    /**
     * 批量插入数据
     * @param  array  $data [键值对的二维数组，以字段名为键]
     * @return [type]       [一维数组，insert_id, total_rows]
     */
    public static function multiInsert($table = '', $data = [])
    {
        if (empty($data)) {
            return [0,0];
        }
        $str = '';
        foreach ($data as $v) {
            // 要插入表的字段
            $field = implode(',', array_keys($v));
            // 拼接要插入的值
            $str .= '(\'' . implode("','", $v) . '\'),';
        }
        // 去除最后一个逗号
        $values = rtrim($str, ',');
        // 拼接sql语句
        $sql = "INSERT INTO $table ($field) VALUES $values";
        return DB::query(Database::INSERT, $sql)->execute();
    }

    /**
     * 推送消息
     * @param  [type] $user_number     [description]
     * @param  [type] $user_department [description]
     * @param  [type] $msg             [description]
     * @return [type]                  [description]
     */
    public static function pushMsg($user_number, $user_department_id, $msg, $qos = 0, $msg_type = 'logout', $msg_id, $yiyuan_id = 0)
    {
        // 获取推送实例
        $conn = PhpsamMqtt::instance();
        //start initialise the connection
        $host = Yaconf::get("config$yiyuan_id.mqtt.host");
        $port = Yaconf::get("config$yiyuan_id.mqtt.port");
        $conn->connect(SAM_MQTT, array(SAM_HOST => $host,
                                 SAM_PORT => $port));

        $msg_arr = array('msg_id' => $msg_id,'title' => $msg_type, 'content' => $msg);

        if (!$conn) {
            return false;
        }

        $options = [
            'SAM_MQTT_QOS' => $qos,
        ];

//        $query = DB::select('u.id,u.user_department_id,s.user_number,s.shebei_id')
//                    ->from('yiyuan_user as u')
//                    ->join('yiyuan_sess as s', 'RIGHT')
//                    ->on('s.user_number', '=', 'u.user_number')
//                    ->where('s.yiyuan_id', '=', $yiyuan_id);
//        if ($msg_type == 'logout') {
//            $query->and_where('u.user_number', '=', $user_number);
//        } else{
//            $query->and_where('u.user_department_id', '=', $user_department_id);
//            $query->and_where('s.shebei_id', '!=', $_REQUEST['shebei_id']);
//        }
        if($msg_type == 'xin_yizhu')
        {
            $options = [
                'SAM_MQTT_QOS' => $qos,
            ];
            $target = 'zpdydhl/' . $_REQUEST['user_department_id'] . '/' . $_REQUEST['user_number']."/". $_REQUEST['shebei_id'];
            // 推送消息
            $msg = json_encode($msg_arr);
           // file_put_contents('zh.log', print_r(array(date('Y-m-d H:i:s'), __LINE__, __METHOD__, $target, TRUE)));
            //file_put_contents('zh.log', print_r(array(date('Y-m-d H:i:s'), __LINE__, __METHOD__, $target), TRUE));
            $rc     = $conn->send('topic://' . $target, $msg, $options);

            $state = 1;
            // 记录推送日志
            if($rc)
            {
                self::insertPushMsgLog($msg_id, $msg, $msg_type, $_REQUEST['user_number'], $_REQUEST['user_department_id'], $state);
            }
            $conn->Disconnect();
            return $rc;
        }

        $query = DB::select('user_department_id,user_number,shebei_id')
            ->from('yiyuan_sess')
            ->where('yiyuan_id', '=', $yiyuan_id)
            ->and_where("expiry",">",time());

        if ($msg_type == 'logout') {
            $query->and_where('user_number', '=', $user_number);
        } else{
        	$query->and_where('user_department_id', '=', $user_department_id);
        	$query->and_where('shebei_id', '!=', $_REQUEST['shebei_id']);
        }


        $user_departments = $query->execute()->as_array();

        foreach ($user_departments as $value) {
            // 如果消息类型是shuaxin_yizhu，则剔除执行该医嘱的护士账号，不推送消息
            if ($msg_type != 'logout' && $value['user_number'] == $user_number &&  $value['shebei_id'] == $_REQUEST['shebei_id']) {
                continue;
            }
            // 拼接推送的主题 字符串
            $target = 'zpdydhl/' . $value['user_department_id'] . '/' . $value['user_number']."/". $value['shebei_id'];
            // 推送消息
            $msg = json_encode($msg_arr);
            $rc     = $conn->send('topic://' . $target, $msg, $options);

            $state = 1;
            // 记录推送日志
            if($rc)
            {
                self::insertPushMsgLog($msg_id, $msg, $msg_type, $value['user_number'], $value['user_department_id'], $state);
            }
        }
        // 关闭
        $conn->Disconnect();
        return $rc;
    }

    /**
     * 记录推送日志
     * @param  [type]  $content              [消息内容]
     * @param  [type]  $msg_type             [消息类型]
     * @param  [type]  $user_number          [护士账号]
     * @param  [type]  $user_department_code [科室code]
     * @param  integer $state                [发送状态]
     * @return [type]                        [description]
     */
    private static function insertPushMsgLog($msg_id, $content, $msg_type, $user_number, $user_department_code, $state = 1)
    {
        $data = array(
            'msg_id' => $msg_id,
            'msg_content' => $content,
            'msg_type' => $msg_type,
            'user_number' => $user_number,
            'user_department_code' => $user_department_code,
            'expiry_time' => time(),
            'count' => 1,
            'send_time' => time(),
            'state' => 1, //消息推送状态,1=成功,
        );

        $affect_rows = DB::insert('pushmsg_log', array_keys($data))->values(array_values($data))->execute();
        return $affect_rows;
    }

    //登陆之后写入session
     public static function saveSession($user_number,$shebei_id,$sessionID)
     {
         $session=Yaf_Session::getInstance();
         $session->user_number = $user_number;
         $session->shebei_id = $shebei_id;
         $session->session_id = $sessionID;

     }

}
